package cn.acewill.yxd.yunxundian.ui.follow_up;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.YXDAPP;
import cn.acewill.yxd.yunxundian.model.CommonMapBean;
import cn.acewill.yxd.yunxundian.model.Employee;
import cn.acewill.yxd.yunxundian.model.Schedule;
import cn.acewill.yxd.yunxundian.model.Shop;
import cn.acewill.yxd.yunxundian.model.t_Feedback_Main;
import cn.acewill.yxd.yunxundian.model.t_Feedback_Row;
import cn.acewill.yxd.yunxundian.ui.MainActivity;
import cn.acewill.yxd.yunxundian.ui.follow_up.adapter.FollowUpMainAdapter;
import cn.acewill.yxd.yunxundian.ui.follow_up.nodeStruct.FU_main;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link FollowupListFragment#newInstance} factory method to
 * create an instance of this fragment.
 */

@ContentView(R.layout.fragment_followup_list)
public class FollowupListFragment extends Fragment {
    protected DbManager db = x.getDb(new YXDAPP().getDaoConfig());
    public static final int FOLLOW_UP_MAIN = 1;
    public static final int FOLLOW_UP_PASS = 2;
    public static final int FOLLOW_UP_HISTORY = 3;
    private static final String[] err_text = {"没有数据","无未完成追踪","无待确认追踪","无已完成追踪"};
    private static final String ARG_PARAM1 = "type";
    private int type;
    @ViewInject(R.id.myRecycle)
    private RecyclerView mRecyclerView;
    @ViewInject(R.id.errorText)
    private TextView errorText;

    FollowUpMainAdapter fumAdapter;

    public FollowupListFragment() {
        // Required empty public constructor
    }

    public static FollowupListFragment newInstance(int type) {
        FollowupListFragment fragment = new FollowupListFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_PARAM1, type);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            type = getArguments().getInt(ARG_PARAM1,0);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return  x.view().inject(this, inflater, container);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState){
        super.onActivityCreated(savedInstanceState);
        //Log.i("FollowupListFragment","onActivityCreated");
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        switch(type){
            case FOLLOW_UP_MAIN:
            case FOLLOW_UP_PASS:
            case FOLLOW_UP_HISTORY:
                List<FU_main> fuMainList = createFUMainList();
                if(fuMainList.size()>0){
                    fumAdapter = new FollowUpMainAdapter(getActivity(),fuMainList);
                    mRecyclerView.setAdapter(fumAdapter);
                    mRecyclerView.setItemAnimator(new DefaultItemAnimator());
                }else{
                    showErrInfo(err_text[type]);
                }
                break;
            default:
                showErrInfo(err_text[0]);
                break;
        }
    }

    private void showErrInfo(String errStr){
        errorText.setText(errStr);
        errorText.setVisibility(View.VISIBLE);
    }

    private List<FU_main> createFUMainList(){
        List<FU_main> fuMainList = new ArrayList<>();
        String op = type==FOLLOW_UP_HISTORY?">":"=";

        try {
            List<t_Feedback_Main> tfmList = db.selector(t_Feedback_Main.class)
                                            .where("states",op,0)
                                            .findAll();
            if (tfmList!=null&&tfmList.size()>0){
                for (t_Feedback_Main tfm:tfmList) {
                    if(tfm.getempid()==MainActivity.id || isShopManOfTFM(tfm.getId())) {
                        if((type==FOLLOW_UP_MAIN && isWaitPass(tfm.getId())) || (type==FOLLOW_UP_PASS && !isWaitPass(tfm.getId()))){
                            continue;
                        }
                        FU_main node = new FU_main();
                        Schedule schedule = db.selector(Schedule.class).where("ID", "=", tfm.getschid()).findFirst();
                        if (schedule == null)
                            continue;
                        CommonMapBean cmb = db.selector(CommonMapBean.class).where("ServerId", "=", tfm.getschid()).findFirst();
                        Employee emp = db.selector(Employee.class).where("ID", "=", tfm.getempid()).findFirst();
                        Shop shop = db.selector(Shop.class).where("ID", "=", tfm.getshopid()).findFirst();
                        node.schName = schedule.getTitle()+"["+(cmb != null ? cmb.getCmValue() : "")+"]";
                        node.shopName = "门店：" + (shop != null ? shop.getShopName() : "");
                        node.empName = "评估人：" + (emp != null ? emp.getFirstName() : "");
                        node.exTime = "截至日期：" + tfm.getexTime().replace('T', ' ');
                        node.id = tfm.getId();
                        node.states = tfm.getstates();
                        node.schId = tfm.getschid();
                        node.empId = tfm.getempid();
                        fuMainList.add(node);
                    }
                }
            }
        } catch (DbException e) {
            e.printStackTrace();
        }

        return fuMainList;
    }

    private boolean isShopManOfTFM(int tfmId){
        try {
            List<t_Feedback_Row> tfrList = db.selector(t_Feedback_Row.class)
                    .where("t_FB_M_ID","=",tfmId)
                    .findAll();
            for(t_Feedback_Row tfr:tfrList){
                if(tfr.getshopmanid() == MainActivity.id) {
                    return true;
                }
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
        return false;
    }

    private boolean isWaitPass(int tfmId){
        boolean ret = false;
        try {
            List<t_Feedback_Row> tfrList = db.selector(t_Feedback_Row.class)
                    .where("t_FB_M_ID","=",tfmId)
                    .findAll();
            if(tfrList.size()>0)
                ret = true;
            for(t_Feedback_Row tfr:tfrList){
                if(tfr.getstates() != 222) {
                    ret = false;
                    break;
                }
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
        return ret;
    }
}
